package com.oujia.cloud.cloudcommon.util;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import lombok.extern.slf4j.Slf4j;


import java.io.File;
import java.nio.file.Paths;

@Slf4j
public class JdyunOssUtils {

    /**
     * Access Key ID
     */
    static final String accessKey = "1D85F2DB80B0F56DD244078684E555FA";
    /**
     * Access Key Secret
     */
    static final String secretKey = "CAD4385B8AF1F28364268ED8A6631E89";
    /**
     * 上传地址
     */
    static final String endpoint = "http://s3.cn-south-1.jcloudcs.com";

    /**
     * 方法说明：JDYun 上传
     */
    public static void JDYunUpload(String bucketName, String filePath) {
        try {
            String key = Paths.get(filePath).getFileName().toString();
            initS3().putObject(bucketName, key, new File(filePath));
            log.info("京东oss上传成功：" + filePath);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        }
    }

    /**
     * 方法说明：JDYun 上传
     */
    public static void JDYunDelete(String bucketName, String objectKey) {
        try {
            initS3().deleteObject(bucketName, objectKey);
            log.info("京东oss删除成功：" + objectKey);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        }
    }

    /**
     * 方法说明：初始化JDYun
     */
    public static AmazonS3 initS3() {
        System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
        ClientConfiguration config = new ClientConfiguration();

        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
        return s3;
    }

}
